package net.jiastudy.biz.datasync.strategy.ypi;

import net.jiastudy.biz.datasync.DataSyncStrategy;
import net.jiastudy.biz.datasync.strategy.ypi.bean.VBzxbDw;
import net.jiastudy.biz.datasync.strategy.ypi.bean.VJzgjbxxJbxx;
import net.jiastudy.biz.datasync.strategy.ypi.mapper.VBzxbDwMapper;
import net.jiastudy.biz.datasync.strategy.ypi.mapper.VJzgjbxxJbxxMapper;
import net.jiastudy.biz.enums.DeptType;
import net.jiastudy.biz.sys.entity.Dept;
import net.jiastudy.biz.sys.service.DeptService;
import net.jiastudy.biz.user.entity.User;
import net.jiastudy.biz.user.service.UserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component("ypiDataSyncStrategy")
public class YpiDataSyncStrategyImpl implements DataSyncStrategy {
    @Resource
    private VBzxbDwMapper vbzxbdwMapper;

    @Resource
    private VJzgjbxxJbxxMapper vJzgjbxxJbxxMapper;

    @Resource
    private DeptService deptService;

    @Resource
    private UserService userService;

    @Override
    public boolean syncDepts() {
        List<VBzxbDw> tmpDepts = vbzxbdwMapper.selectList(null);
        if (null != tmpDepts) {
            for (VBzxbDw tmpDept : tmpDepts) {
                if (tmpDept.getSsdwdm() == null || tmpDept.getSsdwdm().isEmpty()) {
                    Dept dbDept = deptService.getDeptByCode(tmpDept.getDwdm());
                    if (null == dbDept) {
                        Dept dept = new Dept();
                        dept.setName(tmpDept.getDwbzmc());
                        dept.setCode(tmpDept.getDwdm());
                        dept.setType(DeptType.other);

                        deptService.createDept(dept);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public boolean syncTeacher() {
        List<VJzgjbxxJbxx> tmpUsers = vJzgjbxxJbxxMapper.selectList(null);
        if (null != tmpUsers) {
            List<Dept> depts = deptService.findAllDepts();
            Map<String, Dept> deptMap = new HashMap<>();
            for (Dept dept : depts) {
                deptMap.put(dept.getCode(), dept);
            }
            for (VJzgjbxxJbxx tmpUser : tmpUsers) {
                User dbUser = userService.getUserByUsername(tmpUser.getZgh());
                if (null == dbUser) {
                    User user = new User();
                    user.setName(tmpUser.getXm());
                    user.setUsername(tmpUser.getZgh());
                    user.setPassword(tmpUser.getZgh());
                    if (null != tmpUser.getDwdw() && deptMap.containsKey(tmpUser.getDwdw())) {
                        user.setDeptId(deptMap.get(tmpUser.getDwdw()).getId());
                    }

                    userService.createUser(user);
                }
            }
        }

        return true;
    }
}
